package processes

import "fmt"

// 这个实例在整个服务器中有且只有一个，很多地方都要用，所以定义为全局变量

var userManagerProcess *UserManagerProcess

type UserManagerProcess struct {
	onlineUsers map[int]*UserProcess
}

func init() {
	userManagerProcess = &UserManagerProcess{onlineUsers: make(map[int]*UserProcess, 1024)}
}

func (userMgr *UserManagerProcess) AddOnlineUser(up *UserProcess) {
	for _, onlineUser := range userMgr.onlineUsers {
		go onlineUser.ServerNotifyOtherOnlineUsers(up.userId)
	}
	userMgr.onlineUsers[up.userId] = up
}

func (userMgr *UserManagerProcess) DelOnlineUser(userId int) {
	delete(userMgr.onlineUsers, userId)
}

func (userMgr *UserManagerProcess) GetAllOnlineUser() map[int]*UserProcess {
	return userMgr.onlineUsers
}

func (userMgr *UserManagerProcess) GetOnlineUserById(userId int) (*UserProcess, error) {
	up, ok := userMgr.onlineUsers[userId]
	if ok {
		return up, nil
	}
	return nil, fmt.Errorf("找不到用户[%d]", userId)
}

func (userMgr *UserManagerProcess) ServerNotifyOthersNewFriend(userId int, userName string) {
	for _, onlineUser := range userMgr.onlineUsers {
		go onlineUser.ServerNotifyOthersNewFriend(userId, userName)
	}
}
